<script setup lang="ts">
  import DynamicForm from '@/components/common/dynamicForm/DynamicForm.vue';
  import { DynamicFormOption, DynamicItem } from '@/components/types';
  import { useLocale } from '@/locales/useLocale';
  import * as Mock from 'mockjs';
  import { computed, ref } from 'vue';
  import { useMobile } from '@/hooks/core/useMobile';
  import { useAuthStore } from '@/store/module/useAuthStore';
  import { IUserLoginParam } from '@/api/types';
  import { useRouter } from 'vue-router';

  const { t } = useLocale();

  const captchaUrl = ref(import.meta.env.VITE_USER_API_URL + '/captcha?time=' + new Date());
  const imgClickHandle = () => {
    captchaUrl.value = import.meta.env.VITE_USER_API_URL + '/captcha?time=' + new Date();
  };
  const schema = {
    username: 'required',
    password: 'required',
    code: 'required',
    userAgreement: 'userAgreement',
  };
  const initValues = {
    username: '',
    password: '',
    code: '',
    userAgreement: false,
  };
  const userLoginFormOption = [
    {
      is: DynamicItem.INPUT,
      name: 'username',
      placeholder: 'message.sys.login.accountPlaceholder',
      requiredField: true,
    },
    {
      is: DynamicItem.INPUT,
      name: 'password',
      placeholder: 'message.sys.login.passwordPlaceholder',
      type: 'password',
      requiredField: true,
      showPassword: true,
    },
    {
      is: DynamicItem.CAPTCHA,
      name: 'code',
      placeholder: 'message.sys.login.smsPlaceholder',
      requiredField: true,
      captchaUrl: captchaUrl,
      imgClick: imgClickHandle,
    },
    {
      name: 'userAgreement',
      is: DynamicItem.CHECKBOX,
      requiredField: true,
      checkboxContent: 'message.sys.login.policy',
    },
  ] as DynamicFormOption[];
  const loading = ref(false);
  const router = useRouter();
  const onSubmit = (values: IUserLoginParam, formTool: Recordable) => {
    const authStore = useAuthStore();
    loading.value = true;
    authStore.userLogin(values, router, () => {
      imgClickHandle();
      formTool.resetForm();
      loading.value = false;
    });
  };
  const isMobile = useMobile();
  const size = computed(() => {
    return isMobile.value ? 'default' : 'large';
  });
</script>

<template>
  <DynamicForm
    as="ElForm"
    :validation-schema="schema"
    :initialValues="initValues"
    :options="userLoginFormOption"
    @on-submit="onSubmit"
    :size="size"
    :loading="loading"
    animate-class="enter-x"
  />
</template>

<style lang="scss"></style>
